package replicant3.replicant3;


import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.StringTokenizer;


public class UDP extends Thread{
	String serverName; 
	int portNo;
	replica_pratik tempServer = null;
	
	UDP(String serverName, int portNo, replica_pratik server)
	{
		this.serverName = serverName;
		this.portNo = portNo;
		tempServer = server;
	}
	
	public void run() {
		
		System.out.println("UDP Server started : "+serverName);
		DatagramSocket host = null;
		try{
			
			host = new DatagramSocket(portNo);
			
			byte [] receiveData = new byte [1024];
			byte [] sendData = new byte [1024];
			ArrayList<String> ans = new ArrayList<String>();
	
			while(true)
			{
				DatagramPacket request = new DatagramPacket(receiveData, receiveData.length);
				host.receive(request);
				
				String check = new String(receiveData);
		
				int i =0 ;
				
				if(check.startsWith("First")){
			
					StringTokenizer str = new StringTokenizer(check, ",");
				 
					while(str.hasMoreTokens()){
						
						String completeString = str.nextToken();
						StringTokenizer str1 = new StringTokenizer(completeString, ":");
						if(i <= 4){
							str1.nextToken();
							
							ans.add(str1.nextToken());
							}
					   i++;
						
					}
					
					
			for(int ii = 0 ; ii < 5 ; ii++){
					tempServer.myMultimap.put(ans.get(3), ans.get(ii));
				}
					 tempServer.increase(ans.get(3), ans.get(4));

					sendData=("Successfully deleted").getBytes();
					DatagramPacket reply = new DatagramPacket(sendData, sendData.length,request.getAddress(),request.getPort());
					host.send(reply);
					
				}else{
				
				int noOfRecords = tempServer.getlocalCountonline();
				int gn = tempServer.getlocalCountoffline();
                sendData=(serverName+":"+noOfRecords+":"+gn).getBytes();
				DatagramPacket reply = new DatagramPacket(sendData, sendData.length,request.getAddress(),request.getPort());
				host.send(reply);
			
			 }
			}
			
		}catch(SocketException e){System.out.println("Socket "+e.getMessage());
		}catch(Exception e){System.out.println(e.getMessage());
		}finally {if(host != null){host.close();}}
		
	}

}
